/**
 * @Description: 
 * @Date: 2020-03-24 10:42:32
 */
/**
 * @Description: 资源目录管理
 * @Date: 2020-03-23 10:46:13
 */

$(function() {
    // 根节点id(自定义)
    var treeObj;
    // 获取机构上下级树
    var orgData = [];
    $(function() {
        $.ajax({
            type: 'post',
            async: false,
            url: '/BaseAshx/Resource/CatalogManage.ashx',
            data: {
                mtype: 'CatalogManage_GetTreeList'
            },
            datatype: 'json',
            success: function(res) {
                if (typeof res == 'string') {
                    res = JSON.parse(res);
                }
                console.log(res);
                if (res.code == 200) {
                    var data = res.data;
                    data.forEach(function(item, index) {
                        if (item.ID) {
                            var mapResult = {
                                "id": item.ID,
                                "name": item.NAME,
                                "pId": item.PID,
                                "POSITION": item.POSITION,
                                "ADDRESS": item.ADDRESS
                            };
                            if (!item.PID) {
                                mapResult.open = true;
                            }
                            orgData.push(mapResult);
                        }
                    });
                    // console.log(orgData);
                    queryHandler(orgData);
                }
            },
            error: function(err) {
                console.log(err);
            }
        });
    })

    var setting = {
        view: {
            addDiyDom: addDiyDom,
            expandSpeed: 0,
        },
        data: {
            simpleData: {
                enable: true //确定 zTree 初始化时的节点数据、异步加载时的节点数据、或 addNodes 方法中输入的 newNodes 数据是否采用简单数据模式 (Array) 
            }
        },
        callback: {
            // 点击
            onClick: zTreeOnClick,
            // 展开
            onExpand: zTreeOnExpand,
            // 关闭
            onCollapse: zTreeOnCollapse
        }
    };

    /**
     * 自定义DOM节点
     */
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 15;
        var liObj = $("#" + treeNode.tId);
        var aObj = $("#" + treeNode.tId + "_a");
        var switchObj = $("#" + treeNode.tId + "_switch");
        var icoObj = $("#" + treeNode.tId + "_ico");
        var spanObj = $("#" + treeNode.tId + "_span");
        aObj.attr('title', '');
        aObj.append('<div class="divTd swich fnt" style="width:40%"></div>');
        var div = $(liObj).find('div').eq(0);

        $('span[id^="dataTree"][id$="ico"]').css("margin-top", "9px");
        //从默认的位置移除
        switchObj.remove();
        spanObj.remove();
        icoObj.remove();
        //在指定的div中添加
        div.append(switchObj);
        div.append(spanObj);
        //隐藏了层次的span
        var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode
            .level) + "px'></span>";
        switchObj.before(spaceStr);
        //图标垂直居中
        icoObj.css("margin-top", "9px");
        switchObj.after(icoObj);
        var editStr = '';
        // //宽度需要和表头保持一致
        editStr += '<div class="divTd" style="width:30%">' + treeNode.POSITION + '</div>';
        editStr += '<div class="divTd" style="width:30%">' + treeNode.ADDRESS + '</div>';
        // console.log(treeNode);
        aObj.append(editStr);
    }
    //初始化列表
    function queryHandler(zTreeNodes) {
        //初始化树
        //第一个参数为zTree的DOM容器，第二个为zTree设置详情可见官网api,第三个为zTree的节点数据
        treeObj = $.fn.zTree.init($("#dataTree"), setting, zTreeNodes);
        //添加表头
        var li_head = '<li class="head">' +
            '<a>' +
            '<div class="divTd" style="width:40%">资源目录</div>' +
            '<div class="divTd" style="width:30%">数据库名称</div>' +
            '<div class="divTd" style="width:30%">数据地址</div>' +
            '</a>' +
            '</li >';
        var rows = $("#dataTree").find('li');
        if (rows.length > 0) {
            //rows.eq(0).before(li_head);
        } else {
            $("#dataTree").append(li_head);
            $("#dataTree").append(
                '<li ><div style="text-align: center;line-height: 30px;" >无符合条件数据</div></li>');
        }
    }

    // 当前选中节点
    var nowNode = {
        id: ''
    }

    // 点击返回根目录
    $('.returnBtn').on('click', function(e) {
        var $this = $(this);
        if (!$this.hasClass('unable')) {
            $this.addClass('unable');
            $('.deleteBtn, .editBtn, .returnBtn, .userBtn, .powerBtn').addClass('unable');
            nowNode = nowNode = {
                id: ''
            }
            $('.curSelectedNode').removeClass('curSelectedNode');
            $('#direction').html('根目录');
        }
    });

    function zTreeOnClick(event, treeId, treeNode) {
        if (nowNode == treeNode) {
            // 重复点击了 
            $('.returnBtn').click();
            return;
        }
        // 修改当前节点
        nowNode = treeNode;
        $('#direction').html(treeNode.name);
        $('.addBtn, .deleteBtn, .editBtn, .returnBtn, .userBtn, .powerBtn').removeClass('unable');
        console.log(treeNode);
    }

    function zTreeOnExpand(event, treeId, treeNode) {
        //alert(treeNode.tId + ", " + treeNode.name);
    }

    function zTreeOnCollapse(event, treeId, treeNode) {
        //alert(treeNode.tId + ", " + treeNode.name);
    }

    var optionHtml = `<option style='display: none'></option>`;
    $.ajax({
        type: 'post',
        async: false,
        url: '/BaseAshx/Resource/CatalogManage.ashx',
        data: {
            mtype: 'CatalogManage_GetDataBaseList'
        },
        datatype: 'json',
        success: function(res) {
            if (typeof res == 'string') {
                res = JSON.parse(res)
            }
            console.log(res);
            if (res.code == 200) {
                res.data.map(function(item, index) {
                    optionHtml += `<option>` + item.NAME + `</option>`
                })
            } else {
                console.log(res.msg)
            }
        },
        error: function(err) {
            console.log(err);
            var msg = '';
            if (err.status == 405) {
                msg = '未登录, 请先登录';
                setTimeout(function() {
                    top.location.href = '/';
                }, 500);
            } else {
                msg = '数据获取失败';
            }
            layui.layer.msg(msg, {
                shade: 0.3,
                time: 1000 // 1秒关闭
            });
        }
    });

    // 增加事件 参数：当前id，当前level，增加的简称，增加的全称
    $('.addBtn').on('click', function() {
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        var html = `
        <div>
            <span>资源目录名称：</span>
            <input id="nameInput" type="text" class="layui-layer-input"  autocomplete="off" maxlength="20"><br>
            <span>数据库名称：</span>
            <select id="dbNameInput" type="" class="layui-layer-input" autocomplete="new-password"  maxlength="200">
                ` + optionHtml + `
                </select><br>
            <span>数据地址：</span>
            <input id="addressInput" type="text" class="layui-layer-input" autocomplete="off" maxlength="20"><br>
        </div>
        `;
        var content = '<div>' + html + '</div>';
        layer.open({
            id: 1,
            type: 1,
            title: '新建资源目录',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['保存', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function(index, layero) {
                layer.close(index);
            },
            btn1: function(index, layero) {
                var name = layero.find('#nameInput').val();
                var dbNameInput = layero.find('#dbNameInput').val();
                var addressInput = layero.find('#addressInput').val();
                if (!name) {
                    layui.layer.msg('请输入资源目录名称', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                // if (!dbNameInput) {
                //     layui.layer.msg('请选择数据库名称', {
                //         shade: 0.3,
                //         time: 1000 // 1秒关闭
                //     });
                //     return;
                // }
                // if (!addressInput) {
                //     layui.layer.msg('请输入地址', {
                //         shade: 0.3,
                //         time: 1000 // 1秒关闭
                //     });
                //     return;
                // }
                $.ajax({
                    type: 'post',
                    async: false,
                    url: '/BaseAshx/Resource/CatalogManage.ashx',
                    data: {
                        mtype: 'CatalogManage_Add',
                        id: nowNode.id,
                        name: name,
                        position: dbNameInput,
                        address: addressInput
                    },
                    datatype: 'json',
                    success: function(result) {
                        result = JSON.parse(result);
                        console.log(result);
                        if (result.code == 200) {
                            // 添加节点
                            var newNode = treeObj.addNodes(nowNode, {
                                id: result.data,
                                "name": name, // 机构简称
                                "POSITION": dbNameInput,
                                "ADDRESS": addressInput
                            }, true);
                            layer.close(index);
                            console.log(nowNode);
                            if (nowNode.id) {
                                var $switchBtn = $("#" + nowNode.tId +
                                    "_switch");
                                var className = $switchBtn.attr('class');
                                if (className.indexOf('_close') >= '0') {
                                    $switchBtn.click();
                                }
                            } else {
                                location.href = location
                            }
                        } else {
                            layui.layer.msg(result.msg, {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function(error) {
                        console.log(error);
                    }
                });
            },
        });
    });

    // 编辑事件 参数：当前id，编辑的东西
    $('.editBtn').on('click', function() {
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        console.log(nowNode);

        var html =
            `<div>
            <span>资源目录名称：</span>
            <input id="nameInput" type="text" class="layui-layer-input" autocomplete="off" maxlength="20" value="` +
            nowNode.name + `"><br>
            <span>数据库名称：</span>
            <select id="dbNameInput" class="layui-layer-input" autocomplete="off"  maxlength="200">
                ` + optionHtml + `
                </select><br>
            <span>数据地址：</span>
            <input id="addressInput" type="text" class="layui-layer-input" autocomplete="off" maxlength="20"><br>
        </div>`
        var content = '<div>' + html + '</div>';
        layer.open({
            id: 2,
            type: 1,
            title: '请编辑资源目录',
            skin: 'layui-layer-prompt',
            content: content,
            btn: ['保存', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function(index, layero) {
                layer.close(index);
            },
            btn1: function(index, layero) {
                var name = layero.find('#nameInput').val();
                var dbNameInput = layero.find('#dbNameInput').val();
                var addressInput = layero.find('#addressInput').val();
                if (!name) {
                    layui.layer.msg('请输入资源目录名称', {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
                // if (!dbNameInput) {
                //     layui.layer.msg('请选择数据库名称', {
                //         shade: 0.3,
                //         time: 1000 // 1秒关闭
                //     });
                //     return;
                // }
                // if (!addressInput) {
                //     layui.layer.msg('请输入地址', {
                //         shade: 0.3,
                //         time: 1000 // 1秒关闭
                //     });
                //     return;
                // }

                $.ajax({
                    type: 'post',
                    async: false,
                    url: '/BaseAshx/Resource/CatalogManage.ashx',
                    data: {
                        mtype: 'CatalogManage_Update',
                        id: nowNode.id,
                        name: name,
                        position: dbNameInput,
                        address: addressInput
                    },
                    datatype: 'json',
                    success: function(result) {
                        result = JSON.parse(result);
                        console.log(result);
                        if (result.code == 200) {
                            // 更新节点
                            nowNode.name = name;
                            nowNode.POSITION = dbNameInput;
                            nowNode.ADDRESS = addressInput;
                            var newNode = treeObj.updateNode(nowNode);
                            $('.curSelectedNode>div').eq(1).html(dbNameInput);
                            $('.curSelectedNode>div').eq(2).html(addressInput);
                            $('span[id^="dataTree"][id$="ico"]').css(
                                "margin-top", "9px");
                            layer.close(index);
                            console.log(nowNode);
                            layui.layer.msg('修改成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        } else {
                            layui.layer.msg(result.msg, {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function(error) {
                        console.log(error);
                    }
                });
            },
        });

        $('#dbNameInput').val(nowNode.POSITION);
        $('#addressInput').val(nowNode.ADDRESS);



    });

    // 删除事件 参数：当前id
    $('.deleteBtn').on('click', function() {
        var $this = $(this);
        if ($this.hasClass('unable')) {
            return;
        }
        console.log(nowNode);
        layer.open({
            // id: 3,
            type: 1,
            title: '删除资源',
            skin: 'layui-layer-prompt',
            content: '<div>' +
                '确定删除当前所资源吗?' +
                '</div>',
            btn: ['确定', '取消'],
            shadeClose: true, //点击遮罩关闭
            btn2: function(index, layero) {
                layer.close(index);
            },
            btn1: function(index, layero) {
                $.ajax({
                    type: 'post',
                    async: false,
                    url: '/BaseAshx/Resource/CatalogManage.ashx',
                    data: {
                        mtype: 'CatalogManage_Delete',
                        id: nowNode.id
                    },
                    datatype: 'json',
                    success: function(result) {
                        result = JSON.parse(result);
                        if (result.code == 200) {
                            // 删除成功
                            var newNode = treeObj.removeNode(nowNode);
                            //$('span[id^="dataTree"][id$="ico"]').css("margin-top", "9px");
                            layui.layer.msg('删除成功', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                            layer.close(index);
                        } else {
                            layui.layer.msg('删除失败', {
                                shade: 0.3,
                                time: 1000 // 1秒关闭
                            });
                        }
                    },
                    error: function(error) {
                        console.log(error);
                    }
                });
            },
        });
    });
});